<script setup lang="ts">
import { onMounted, reactive, Ref, ref } from 'vue'
import DetailedCase from '@/compontent/detailedCase.vue';
import AxiosManager from "@/axios/axiosManager"
import MediatorComment from "@/types/response/mediatorComment";
import useFileStore from '@/stores/fileStore';
const fileAxios = AxiosManager.fileAxios
import useRespondentStore from '@/stores/respondent'
import useUserStore from '@/stores/userStore';
let userStore = useUserStore();
const respondentStore = useRespondentStore();
import {
	addCaseComment, addCaseFeedback,
	getCaseComment,
	getCaseFeedback,
	getCompletedCase,
	getCompletedCaseDetail
} from "@/axios/case/caseReq";
import { ElMessage } from "element-plus";
import ResUtil from "@/utils/resUtil";
import { Case, CaseStatus } from '@/types/response/case';
import Notice from '@/utils/notice';
import PaymentHistory from '@/types/response/paymentHistory';
let fileStore = useFileStore()

//案件列表数据
const tableData = ref([])

const visible2 = ref(false)
const visible3 = ref(false)
onMounted(() => {
	getCaseList()
})

//获取案件列表
function getCaseList() {
	getCompletedCase(respondentStore.id).then(res => {
		res.forEach(item => {
			tableData.value.push(item)
		})
	})

}

const defaultRemarkInfo = {
	commentId: null, //评论id
	comment: '', //评论内容
	starRate: 0, //评分
	createdTime: '', //评论时间
}
const remarkInfo = ref({ ...defaultRemarkInfo })
const remarkCaseIndex = ref(0)

//点击评价调解时
const handleRemarkView = (caseIndex) => {
	remarkCaseIndex.value = caseIndex
	//先查是否有对该案件的该调解员的评价
	getCaseComment(tableData.value[caseIndex].caseId, tableData.value[caseIndex].mediatorId).then(res => {
		if (res) Object.assign(remarkInfo.value, res)
	})
	//如果有，则显示，新增评价显示默认评价内容
	visible2.value = true
}

//评价调解提交
const handleRemarkSubmit = () => {
	if (!remarkInfo.value.commentId) {
		const comment = new MediatorComment()
		comment.userId=userStore.userId;
		comment.caseId = tableData.value[remarkCaseIndex.value].caseId
		comment.mediatorId = tableData.value[remarkCaseIndex.value].mediatorId
		comment.comment = remarkInfo.value.comment
		comment.starRate = remarkInfo.value.starRate
		addCaseComment(comment).then(res => {
			if (res) {
				Notice.success("评价成功")
			}else{
				Notice.error("评价失败")
			}
		})
		setRemarkInfoDefault()
	}
}
//关闭评价调解页面时
const setRemarkInfoDefault = () => {
	remarkCaseIndex.value = 0
	Object.assign(remarkInfo.value, defaultRemarkInfo)
	visible2.value = false
}
const repayHistory:Ref<PaymentHistory[]> = ref([])
//点击案件还款反馈时
const repayCaseIndex = ref(0)
const handleRepayView = (caseIndex) => {
	repayCaseIndex.value = tableData.value[caseIndex].caseId
	//先查询是否有过还款情况反馈,如果有两次记录,则不允许再次提交
	getCaseFeedback(tableData.value[caseIndex].caseId, respondentStore.id).then(res => {
		if (res.length > 0) {
			res.forEach(item => {
				repayHistory.value.push(item)
				const objectName = repayHistory.value[0].paymentProve
				getFileUrlToServer(objectName).then(url => {
					//repayHistory.value[0].paymentProveUrl = url
				})

			})

		}
	})
	visible3.value = true
}
//关闭案件还款反馈页面时
const fileInput = ref()
const setRepayInfoDefault = () => {
	visible3.value = false
	repayHistory.value = []
	//selectedFile.value = null
	if (fileInput.value.value) fileInput.value.value = ''
	repayCaseIndex.value = 0
}
let paymentProveControl: {
	file: File,
	fileUrl: string,
	submit: Function,
	selectFile: Function
} = reactive({
	fileUrl: "",
	file: null,
	selectFile: () => {
		fileStore.selectFile('all').then(res => {
			paymentProveControl.file = res;
		})
	},
	submit: () => {
		let uploadMsg = {
			uuid: null,
			uploadedSize: 0,
		}
		if (paymentProveControl.file) {
			fileStore.uploadFile(paymentProveControl.file, uploadMsg).then(res => {
				const data = {
					caseId: repayCaseIndex.value,
					paymentProve: res.remoteUrl,
					userId: respondentStore.id,
					status: -1
				}
				addCaseFeedback(data).then(res => {
					Notice.success("上传成功");
					visible3.value = false
					repayCaseIndex.value = 0
				})
			})
		}
		else {
			Notice.error("请上传文件");
		}
		visible3.value = false
	}
})
/*上传文件时
//反馈文件上传
const selectedFile = ref(null)
//切换文件时
const handleFileChange = (event) => {
	const file = event.target.files[0];
	if (file) {
		selectedFile.value = file;
	}
};
async function uploadFileToServer(formData) {
	return ResUtil.getData(await fileAxios.request({
		method: 'post',
		url: '/case/feedback/upload',
		data: formData,
		headers: {
			'Content-Type': 'multipart/form-data'
		}
	}))
}

const uploadFile = () => {
	const formData = new FormData();
	formData.append('file', selectedFile.value);
	uploadFileToServer(formData).then(res => {
		const data = {
			caseId: repayCaseIndex.value,
			paymentProve: res,
			userId: respondentStore.id,
			status: -1
		}
		addCaseFeedback(data).then(res => {
			ElMessage.success('上传成功')
			visible3.value = false
			selectedFile.value = null
			repayCaseIndex.value = 0

		}).catch(err => {console.log(err)})
	})
}*/



async function getFileUrlToServer(objectName) {
	return ResUtil.getData(await fileAxios.request({
		method: 'get',
		url: '/case/feedback/getUrl',
		params: { objectName }

	}))
}

async function deleteFileToServer(objectName) {
	return ResUtil.getData(await fileAxios.request({
		method: 'post',
		url: '/case/feedback/delete',
		params: { objectName }

	}))
}
// 控制详细案件弹窗
let detailedDialog = reactive({
	visible: false,
	case: new Case(),
	look(c: Case) {
		detailedDialog.case = c;
		detailedDialog.visible = true;
	},
	close() {
		detailedDialog.visible = false;
	}
})

</script>

<template>
	<el-scrollbar height="500px">
		<el-table :data="tableData" stripe style="width: 100%">
			<el-table-column prop="caseId" label="案件号" width="100" />
			<el-table-column prop="applicantName" label="申请人" width="100" />
			<el-table-column prop="mediatorName" label="调解员" width="100" />
			<el-table-column prop="caseState" label="调解结果" width="100">
				<template #default="scope">
					<el-tag v-if="scope.row.caseState == CaseStatus.fail" type="danger">调解失败</el-tag>
					<el-tag v-if="scope.row.caseState == CaseStatus.success">调解成功</el-tag>
				</template>
			</el-table-column>
			<el-table-column label="操作" width="350">
				<template #default="scope">
					<el-button type="primary" size="small" @click="detailedDialog.look(scope.row)">查看详情</el-button>
					<el-button type="warning" size="small" @click="handleRemarkView(scope.$index)">评价调解</el-button>
					<el-button type="danger" v-if="scope.row.caseState==CaseStatus.success" size="small" @click="handleRepayView(scope.$index)">还款情况反馈
					</el-button>
				</template>
			</el-table-column>
		</el-table>
	</el-scrollbar>
	<el-dialog v-model="visible2" title="评价调解" width="500" :before-close="setRemarkInfoDefault">
		<h3 v-if="remarkInfo.commentId">历史评价</h3>
		<el-form ref="remarkForm" :model="remarkInfo" label-width="100px">
			<el-form-item label="评价内容">
				<el-input type="textarea" v-model="remarkInfo.comment" placeholder="请输入评价内容"
					:readonly="remarkInfo.commentId"></el-input>
			</el-form-item>
			<el-form-item label="评价分数">
				<el-rate v-model="remarkInfo.starRate" :disabled="remarkInfo.commentId"
					:colors="['#99A9BF', '#F7BA2A', '#FF9900']" />
			</el-form-item>
			<el-form-item v-if="remarkInfo.commentId" label="评价时间">
				<el-input :readonly="remarkInfo.commentId" v-model="remarkInfo.createdTime" />
			</el-form-item>
			<el-form-item v-if="!remarkInfo.commentId">
				<el-button :disabled="remarkInfo.starRate==0" type="primary" @click="handleRemarkSubmit">提交评价</el-button>
			</el-form-item>
		</el-form>
	</el-dialog>

	<el-dialog v-model="visible3" title="还款情况反馈" width="500" :before-close="setRepayInfoDefault">

		<div v-if="repayHistory.length > 0" style="margin-top: 10px; ">
			<el-form v-model="repayHistory[0]" label-position="left" label-width="160px">
				<el-form-item label="上一次还款证明:">
					<el-link type="primary" @click="fileStore.download(repayHistory[0].paymentProve)">点击查看</el-link>
				</el-form-item>

				<el-form-item label="审核状态:">
					<el-tag type="success" v-if="repayHistory[0].status == 1">审核通过</el-tag>
					<el-tag type="warning" v-if="repayHistory[0].status == -1">审核中</el-tag>
					<el-tag type="danger" v-if="repayHistory[0].status == 0">审核失败--原由: {{ repayHistory[0].cause ?
						repayHistory[0].cause : '未知原因' }}</el-tag>
				</el-form-item>

			</el-form>

			<!--<p>上一次还款证明:-->
			<!--	<el-link type="primary" :href="repayHistory[0].paymentProveUrl">点击查看</el-link>-->
			<!--</p>-->
			<!--<p>审核状态:{{ repayHistory[0].status == -1 ? '审核中' : repayHistory[0].status == 1 ? '审核通过' : '审核失败' }}</p>-->
			<!--<p v-if="repayHistory[0].status == 0">上一次反馈驳回原因 :{{ repayHistory[0].cause }}</p>-->
		</div>
		<template v-if="repayHistory.length < 2">
			<div style="font-size: large; font-weight: bold ;margin-bottom: 10px">
				{{ repayHistory.length > 0 ? '再次上传还款证明材料:' : '上传还款证明材料:' }}
			</div>
			<div class="file-upload">
				<el-tag @click="paymentProveControl.selectFile()" type="primary" style="cursor: pointer;" effect="dark">
					{{ paymentProveControl.file?.name ? paymentProveControl.file?.name : "选择文件" }}
				</el-tag>
				<br>
				<div style="display: flex;flex-direction: row-reverse;">
					<el-button type="primary" style="margin-left: 20px;" @click="paymentProveControl.submit()">确定</el-button>
				</div>
				
				<!--x<input ref="fileInput" type="file" @change="handleFileChange" />
				<el-button type="primary" @click="uploadFile" :disabled="!selectedFile">上传</el-button>
				-->
			</div>
		</template>
		<template v-else>
			<div>
				<p>您已经上传过两次还款证明材料,如需再次上传,请联系客服人员.</p>
			</div>
		</template>

	</el-dialog>
	<DetailedCase v-model="detailedDialog.visible" :case-id="detailedDialog.case.caseId"></DetailedCase>
</template>

<style scoped lang="css">
.file-upload {
	max-width: 400px;
	margin: auto;
	padding: 20px;
	border: 1px solid #ccc;
	border-radius: 5px;
}

.avatar-uploader .el-upload {
	border: 1px dashed var(--el-border-color);
	border-radius: 6px;
	cursor: pointer;
	position: relative;
	overflow: hidden;
	transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
	border-color: var(--el-color-primary);
}
</style>